package cn.meomis.action;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import cn.meomis.common.entity.Pagination;
import cn.meomis.common.util.DataTableParam;
import cn.meomis.model.Demo;
import cn.meomis.service.DemoService;

//@Scope("prototype") 
@Controller
//@Namespace("/")
@ParentPackage("json-default")
//@Result(name="success", type="json")
public class DemoAction extends BaseAction {

	private static final long serialVersionUID = 1L;
	private SimpleDateFormat dateformat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private Demo demo;
	
	// @Resource
	@Autowired
	private DemoService demoService;

	
	
	@Action(value = "/demoAction", results = { @Result(name = SUCCESS, location = "/manager/modules/demo/index.jsp"),
												@Result(name = "manager", location = "/manager/modules/demo/notice.jsp")})
	@Override
	public String execute() {
		String type = httpServletRequest.getParameter("type");
		List<Demo> demoList = demoService.findAll();
		httpServletRequest.setAttribute("DEMO_LIST", demoList);
		if("manager".equals(type)){
			return "manager";
		}
		return SUCCESS;
	}

/*	@Action(value = "/demoAddAction", results = { @Result(name = SUCCESS, location = "/demoAction.action?type=manager", type = "redirect") })
	public String add() throws UnsupportedEncodingException {
		Demo demo = new Demo();
		String title = httpServletRequest.getParameter("title");
		title = new String(title.getBytes("ISO-8859-1"),"utf-8");
		String content = new String(httpServletRequest.getParameter("content").getBytes("ISO-8859-1"),"utf-8");
		
//		demo.setTitle(httpServletRequest.getParameter("title"));
//		demo.setContent(httpServletRequest.getParameter("content"));
		demo.setTitle(title);
		demo.setContent(content);
		demo.setPublishdate(new Date());
		demoService.save(demo);
		return SUCCESS;
	}*/
	
	@Action(value="/demoAddAction",results=@Result(name="success", type="json"))
	public void addNotice(){
		String result = "success";
		try {
			demo.setPublishdate(new Date());
			demoService.save(demo);
		} catch (Exception e1) {
			e1.printStackTrace();
			result = "error";
		}
		
		httpServletResponse.setContentType("application/Json");
		JSONObject jsonResponse = new JSONObject();	
		try {
			jsonResponse.put("isSorF", result);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		try {
			httpServletResponse.getWriter().print(jsonResponse.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Action(value = "/demoDeleteAction", results = { @Result(name = SUCCESS, location = "/demoAction.action?type=manager", type = "redirect") })
	public String delete() {
		demoService.removeById(Integer.parseInt(httpServletRequest
				.getParameter("id")));
		return SUCCESS;
	}
	
	
	@Action(value = "/noticeDelete", results = @Result(name = "success", type = "json"))
	public void deleteDestination(){
		String reslut = "success";
		try {
			demoService.removeById(Integer.parseInt(httpServletRequest
					.getParameter("id")));
			
		} catch (Exception e1) {
			e1.printStackTrace();
			reslut = "failure";
		}

		httpServletResponse.setContentType("application/Json");
		JSONObject jsonResponse = new JSONObject();	
		try {
			jsonResponse.put("isSorF", reslut);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		try {
			httpServletResponse.getWriter().print(jsonResponse.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@Action(value = "/demoLoginAction", results = { @Result(name = SUCCESS, location = "/demoAction.action?type=manager", type = "redirect" ),
													@Result(name = "login", location = "/login.jsp" )})
	public String login() {
		String username = httpServletRequest.getParameter("username");
		String password = httpServletRequest.getParameter("password");
		if("admin".equals(username) && "admin".equals(password)){
			return SUCCESS;
		}else{
			return "login";
		}
	}
	
	
	@SuppressWarnings({ "unchecked", "unused" })
	@Action(value="/demoListAction")
	public void listDestination() {

		DataTableParam params = null;
		try {
			params = getParam();
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		HashMap<String, String> paramMap = convertToMap(params.getVoList());	
		String sEcho = paramMap.get("sEcho");
		Long iTotalRecords; // total number of records (unfiltered)
		Long iTotalDisplayRecords; //value will be set when code filters companies by keyword
		JSONArray data = new JSONArray(); //data that will be shown in the table

		int pageNumber = (Integer.parseInt(paramMap.get("iDisplayStart")) / Integer.parseInt(paramMap.get("iDisplayLength"))) + 1;

		StringBuffer hql =new StringBuffer( "from Demo demo ");
		if (params.getIsQuery().equalsIgnoreCase("true")) {
			hql.append(" where 1 = 1 ");
			String title = paramMap.get("title").trim();
			String content = paramMap.get("content").trim();
			if (!"".equalsIgnoreCase(title)) {
				hql.append(" and demo.title like '%"+title+"%' ");
			}
			
			if (!"".equalsIgnoreCase(content)) {
				hql.append(" and demo.content like '%"+content+"%' ");
			}
		}
		
		String sCol = paramMap.get("iSortCol_0");
		String sortingColName =  paramMap.get("mDataProp_"+sCol);
		//asc or desc
	    String sdir = paramMap.get("sSortDir_0");
	   
	    if("0".equals(sortingColName)){
//	    	sortingColName = "dest.destination";
	    }else if("1".equals(sortingColName)){
	    	sortingColName = "demo.title";
	    }else if("2".equals(sortingColName)){
	    	sortingColName = "demo.content";
	    }else if("3".equals(sortingColName)){
	    	sortingColName = "demo.publishdate";
	    }
	    
    	if ("desc".equalsIgnoreCase(sdir)) {
	    	hql.append(" order by "+sortingColName +" desc");
	    }else{
	    	hql.append(" order by "+sortingColName );
	    }
	    

		Object[] values = null;
		Pagination pageMqDestination = demoService.pageQueryByHql(hql.toString(), values, hql.toString(), pageNumber, Integer.parseInt(paramMap.get("iDisplayLength")));
		iTotalRecords = pageMqDestination.getTotalCount();
		List<Demo> apps = (List<Demo>) pageMqDestination.getResult();
		List<Demo> companies = new LinkedList<Demo>();
		for(Demo c : apps){
			companies.add(c);
		}
		
		iTotalDisplayRecords = pageMqDestination.getTotalCount();

	
		try {
			JSONObject jsonResponse = new JSONObject();			
			jsonResponse.put("sEcho", sEcho);
			jsonResponse.put("iTotalRecords", iTotalRecords);
			jsonResponse.put("iTotalDisplayRecords", iTotalDisplayRecords);
			int i = 1;
			for(Demo c : companies){
				JSONArray row = new JSONArray();
				row.put(i++);
				row.put(c.getTitle());
				row.put(c.getContent());
				row.put(dateformat.format(c.getPublishdate()));
				row.put(c.getId());
				data.put(row);
			}
			jsonResponse.put("resultList", data);
			httpServletResponse.setContentType("application/Json;charset=utf-8");
			httpServletResponse.getWriter().print(jsonResponse.toString());
			
		} catch (Exception e) {
			e.printStackTrace();
			httpServletResponse.setContentType("text/html");
			try {
				httpServletResponse.getWriter().print(e.getMessage());
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}

	public Demo getDemo() {
		return demo;
	}

	public void setDemo(Demo demo) {
		this.demo = demo;
	}
}
